/* eslint newline-per-chained-call: 0 */
const _ = require('lodash');
const del = require('del');
const g = require('gulp');
const $ = require('gulp-load-plugins')();
const u = require('./gulp.util');
const cfg = require('./config');
const {log, colors} = $.util;

function zip_file_name(type) {
    const today = require('moment')().format('YYMMDD');
    return [cfg.name, type, today].join('-') + '.zip';
}

// 备份源码
g.task('src', () => {
    const fn = zip_file_name('src');
    log(colors.cyan(`zip ${fn} ...`));
    return u.src([
        u.dir([cfg.src.dir, cfg.dev.dir, cfg.test.dir]),
        u.dir([cfg.src.dir, cfg.dev.dir, cfg.test.dir], '.'),
        '.*', u.exclude(['.git/', '.idea/']),
        '*.js', '*.json', '*.md', '*.txt',
        '!schema.*'
    ], {base: '..'})
        .pipe($.zip(fn))
        .pipe(g.dest('.'));
});

const distDir = `${cfg.bin.tmp.dir}/${cfg.name}`;
const libsDir = 'node_modules';
const jsDir = 'bower_components';

// 发布打包
g.task('pub.zip', () => {
    function filter(ext) {
        const expr = `${cfg.name}/${cfg.pub.web.dir}/**/*${ext}`;
        return $.filter(expr, {restore: true});
    }

    const jss_filter = filter('.js');
    const css_filter = filter('.css');
    const html_filter = filter('.html');
    const html_option = {collapseWhitespace: true};

    const fn = zip_file_name('bin');
    log(colors.cyan(`zip ${fn} ...`));
    return u.src([
        u.dir(cfg.bin.dir),
        u.dir(libsDir)
    ], {base: '.'})
        .pipe($.rename(file => {
            if (file.dirname.startsWith(cfg.bin.dir)) {
                file.dirname = '.' + file.dirname.substr(cfg.bin.dir.length);
            }
            file.dirname = `${cfg.name}/${file.dirname}`;
        }))
        .pipe($.filter(file => file.path !== `${cfg.name}/${cfg.bin.dir}`))
        .pipe(jss_filter).pipe($.uglify()).pipe(jss_filter.restore)
        .pipe(css_filter).pipe($.cssmin()).pipe(css_filter.restore)
        .pipe(html_filter).pipe($.htmlmin(html_option)).pipe(html_filter.restore)
        .pipe($.zip(fn)).pipe(g.dest('../..'));
});

// 复制源码
g.task('pub.copy', () => u.copyNew([
    u.dir([cfg.src.dir, cfg.dev.dir]),
    u.dir(cfg.src.dir, '.'),
    '*.js', '*.json'
], distDir, {base: '.'}));

// 清理发布
g.task('clean', () => {
    const files = [
        `${distDir}/**`
    ];
    const args = u.getArgs();
    if (!_.includes(args, '-a')) {
        files.push(`!${distDir}`);
        files.push(`!${distDir}/${libsDir}/**`);
        files.push(`!${distDir}/${jsDir}/**`);
    }
    return del(files);
});

// 执行发布
g.task('pub', ['pub.copy'], () =>
    $.run('bower i && npm i --production && gulp pub.build && gulp pub.zip', {
        cwd: distDir
    }).exec()
);
